package com.ruoyi.common.utils.encry;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

public class AESUtils {
    /**
     * 生成一个12字节（96位）的随机IV（初始化向量）
     * @return 12字节的IV数组
     */
    public static byte[] generateIvTag(int len) {
        byte[] iv = new byte[len]; // 12字节 = 96位
        SecureRandom secureRandom = new SecureRandom();
        secureRandom.nextBytes(iv);
        return iv;
    }

    // 辅助方法：将十六进制字符串转换为 byte[]
    public static byte[] hexStringToByteArray(String hex) {
        int len = hex.length();
        byte[] byteArray = new byte[len / 2]; // 每两个十六进制字符对应一个字节
        for (int i = 0; i < len; i += 2) {
            byteArray[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                    + Character.digit(hex.charAt(i + 1), 16));
        }
        return byteArray;
    }

    public static String decryPtion(byte[] aesKeyBytes, String content, String iv) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        SecretKeySpec aesKey = new SecretKeySpec(aesKeyBytes, "AES");
        byte[] encryptedData = Base64.getDecoder().decode(content);
        Cipher aesCipher = Cipher.getInstance("AES/GCM/NoPadding");
        GCMParameterSpec gcmSpec = new GCMParameterSpec(128, Base64.getDecoder().decode(iv)); // 实际需从请求中获取IV
        aesCipher.init(Cipher.DECRYPT_MODE, aesKey, gcmSpec);
        String decryptedData = new String(aesCipher.doFinal(encryptedData), StandardCharsets.UTF_8);
        return decryptedData;
    }

    public static byte[] encryPtion(byte[] aesKeyBytes, byte[] content, String iv) throws InvalidAlgorithmParameterException, InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException {
        SecretKeySpec aesKey = new SecretKeySpec(aesKeyBytes, "AES");
        GCMParameterSpec gcmSpec = new GCMParameterSpec(128, Base64.getDecoder().decode(iv)); // 实际需从请求中获取IV
        Cipher aesCipher = Cipher.getInstance("AES/GCM/NoPadding");
        // 2. 使用AES加密数据
        aesCipher.init(Cipher.ENCRYPT_MODE, aesKey, gcmSpec);
        byte[] encryptedDataResponse = aesCipher.doFinal(content);
        return encryptedDataResponse;
    }
}
